<template>
  <div class="edit_container">
    <div class="btn_box">
      <el-button @click.stop="goBack">返回</el-button>
    </div>
    <Acupuncture ref="acupuncture" form-type="edit" @asyncInfor="asyncInfor" @addSpeciInfos="addSpeciInfos" :patient-info="patientInfo" :assess-info="assessInfo" :doctor-type="doctorType" />
    <div class="submit_btn_box">
      <el-button type="primary" :loading="submitLoading" @click.stop="submit">保存</el-button>
    </div>
  </div>
</template>

<script>
import Acupuncture from '../../assessSys/components/acupuncture.vue';
import { acupunctureDetail, acupunctureEvaluate } from '../../../api/treatment/acuptreatment.js'
import { queryPatientInfo } from '@/api/residentPhysician/cureBilling.js';
import moment from 'moment';
import { mapGetters } from 'vuex';
import estimate from '@/mixins/estimate.js';

export default {
  name: 'AcupunctureEdit',
  components: { Acupuncture },
  mixins: [estimate],
  data() {
    return {
      assessId: 0,
      type: 0,
      source: 1,
      patientId: 0,
      patientInfo: {},
      assessInfo: {},
      submitLoading: false
    };
  },
  computed: {
    ...mapGetters([
      'user'
    ]),
    doctorType() {
      const sourceMap = {
        1: 'hospital',
        2: 'outpatient',
        3: 'therapists'
      };
      return sourceMap[this.source];
    }
  },
  mounted() {
    this.type = this.$route.query.type || 0;
    this.source = this.$route.query.source;
    this.assessId = this.$route.query.id;
    this.patientId = this.$route.query.patientId;
    this.getAssessInfo();
  },
  methods: {
    // 同步表单信息
    asyncInfor(data) {
      this.assessInfo = data;
    },
    // 列表新增一条数据
    addSpeciInfos() {
      let data = {
        acupunctureDoctor: null,
        afterAcupunctureComplaint: null,
        beforeAcupunctureComplaint: null,
        checkDoctor: null,
        checkInfo: null,
        checkTime: null,
        treatmentDate: null,
        treatmentPart: null,
        isNew: 1
      };
      if (!this.assessInfo.specificAcupunctureInfos) {
        this.assessInfo.specificAcupunctureInfos = [];
      };
      this.assessInfo.specificAcupunctureInfos.push(data);
      this.assessInfo = JSON.parse(JSON.stringify(this.assessInfo));
    },
    getAssessInfo() {
      if (this.assessId === 0 && this.patientId === 0) {
        this.$message.error('缺少医嘱ID或者患者ID');
        return;
      }
      if (this.assessId) {
        acupunctureDetail({
          type: this.type,
          evaluateSource: this.source,
          relationId: this.$route.query.adviceId
        }).then(res => {
          if (res.code === 0) {
            const content = res.content;
            this.patientInfo = {
              patientName: content.patientName,
              gender: content.gender,
              age: content.age,
              department: content.department,
              bedNum: content.bedNum,
              admissionNum: content.admissionNum
            };
            this.assessInfo = {
              ...this.assessInfo,
              ...content,
              specificAcupunctureInfos: content.specificAcupunctureInfos && content.specificAcupunctureInfos.map(item => ({
                treatmentDate: item.date,
                ...item,
              })),
              adlLevel: content.adlLevel && `${content.adlLevel}`,
              afterTreatmentEffect: content.afterTreatmentEffect,
              remarksOther: content.remarksOther,
              stopTreatmentReason: content.stopTreatmentReason,
              recordUser: content.recordUser,
              doctorStamp: content.doctorStamp,
              stampDate: moment(content.date).format('YYYY-MM-DD HH:mm:ss')
            };
          }
        });
      } else {
        queryPatientInfo({
          page: 1,
          size: 10,
          hisPatientId: this.patientId
        }).then(response => {
          const { code, content } = response;
          let patientInfo = {};
          if (code === 0 && content) {
            patientInfo = content[0];
          }
          this.patientInfo = {
            patientName: patientInfo.patientName,
            gender: patientInfo.gender === 0 ? '女' : '男',
            age: patientInfo.age,
            department: patientInfo.departmentName,
            bedNum: patientInfo.bedNum,
            admissionNum: patientInfo.admissionNum
          };
          const estimate2 = this.getEstimate(this.source, this.patientId, 2);
          if (estimate2) {
            const localAssessInfo = this.getAssessInfoByEstimate(estimate2);
            this.assessInfo = {
              ...this.patientInfo,
              ...localAssessInfo,
              evaluateUser: this.user.realname,
              evaluateTime: '/'
            };
          } else {
            this.assessInfo = {
              ...this.patientInfo,
              evaluateUser: this.user.realname,
              evaluateTime: '/'
            };
          }
        }).catch(error => {
          this.$notify({
            title: '提示',
            message: '网络出错，请稍后再试',
            type: 'danger'
          });
        });
      }
    },
    goBack() {
      this.$store.dispatch('tagsView/delView', this.$route);
      this.$router.back();
    },
    submit() {

      if (this.assessId) {
        this.$refs.acupuncture.getFormData().then(data => {
          let deepData = JSON.parse(JSON.stringify(data));
          deepData.specificAcupunctureInfos && deepData.specificAcupunctureInfos.forEach(item => {
            item.checkTime && (item.checkTime = item.checkTime.replace(" ", "T"));
            item.treatmentDate && (item.treatmentDate = item.treatmentDate.replace(" ", "T"));
          });
          deepData.stampDate && (deepData.stampDate = deepData.stampDate.replace(" ", "T"));
          this.submitLoading = true;
          const requestData = {
            relationId: this.$route.query.adviceId,
            evaluateSource: this.source,
            ...deepData
          };
          acupunctureEvaluate(requestData).then(res => {
            if (res.code === 0) {
              this.$message.success('保存成功');
              this.$store.dispatch('tagsView/delView', this.$route);
              this.$router.back();
            } else {
              this.$message.error(res.msg || '保存失败，请稍后重试');
            }
          }).catch(error => {
            this.$message.error('保存数据时发生网络错误，请稍后重试');
          }).finally(() => {
            this.submitLoading = false;
          });
        });
      } else {
        this.$refs.acupuncture.saveLocalFormData(this.source, this.patientId).then(() => {
          this.$message.success('本地保存成功');
          this.$store.dispatch('tagsView/delView', this.$route);
          this.$router.back();
        }).catch(error => {
          this.$message.error('本地保存失败，请稍后重试');
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import url("./style.scss");
</style>
